package com.ghostmonk.net
{
	import caurina.transitions.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.URLRequest;

	public class TrackableLoader extends Loader
	{
		private var _preloader:MovieClip;
		private var _url:URLRequest;
		private var _readyFrame:int;
		
		public function TrackableLoader(url:URLRequest, preloader:MovieClip)
		{	
			_url = url;
			_preloader = preloader;
			
			_preloader.addEventListener("buildInFinished", preloaderReady);
			_preloader.addEventListener("buildOutFinished", preloaderFinished);
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		
		private function onAddedToStage(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			stage.addEventListener(Event.RESIZE, onResize);
			onResize();
			stage.addChild(_preloader);
		}
		
		private function onProgress(e:ProgressEvent):void 
		{
			var percent:Number = e.bytesTotal != 0 ? e.bytesLoaded / e.bytesTotal : 0;
			_preloader.gotoAndStop(Math.ceil(percent * 100) + _readyFrame);
		}
		
		private function onComplete(e:Event):void 
		{	
			_preloader.gotoAndPlay(_readyFrame + 100);
		}
		
		private function preloaderReady(e:Event):void
		{
			_readyFrame = _preloader.currentFrame;
			contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);			
			
			load(_url);
		}
		
		private function preloaderFinished(e:Event):void
		{
			contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);	
			stage.removeEventListener(Event.RESIZE, onResize);
			stage.removeChild(_preloader);
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function onResize(e:Event = null):void
		{
			_preloader.x = stage.stageWidth/2;
			_preloader.y = stage.stageHeight/2;
		}
				
	}
}